package com.hmy.cornpestdet.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;

public class SendImageToPython {
    // Flask服务器的URL
    private static final String URL = "http://127.0.0.1:5000/receiveBase64Img";
    private static final String BASE_IMAG0E_PATH = "E:/coding/project/project java/CornPestDet/src/main/resources/static/images";

    public static boolean sendImage(String imageName) throws IOException {
        //获取图片的base64编码
        String base64Image = getBase64Image(imageName);
        if(base64Image == null) return false;
        sendImage(base64Image);
        return true;
    }

    private static String getBase64Image(String imageName){
        File imageFile = new File(BASE_IMAG0E_PATH + "/" + imageName);
        Path imagePath = imageFile.toPath();
        try {
            // 假设你有一个图片的字节数组
            byte[] imageBytes = Files.readAllBytes(imagePath);
            // 将图片字节数组编码为Base64字符串
            return Base64.getEncoder().encodeToString(imageBytes);
        }
        catch (Exception e) {
            return null;
        }

    }

    private static boolean sendPostRequest(String base64Image){
        // 发送POST请求
        try {
            //设置请求头
            URL url = new URL(URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);

            // 准备POST请求体
            String postParams = "img=" + base64Image;
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = postParams.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("Server responded with OK");
            } else {
                System.out.println("Server responded with code: " + responseCode);
            }
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}



